const db=require('../db/index')
const moment = require('moment');



//新增文章
exports.addArtcle=(req,res)=>{
    var current_time =  moment(Date.now()).format('YYYY-MM-DD HH:mm:ss')
    const articleInfo={
        title:req.body.title,
        cate_id:req.body.cate_id,
        content:req.body.content,
        state:req.body.state,
        cover_img:req.body.cover_img,
        pub_date:current_time,
        author_id:req.user.id,
        is_delete:0
    }
    console.log(articleInfo);
    const sql='insert into ev_article set ?'
    db.query(sql,articleInfo,(err,result)=>{
        if(err) return res.cc(err.message)
        if(result.affectedRows!==1) return res.cc('新增文章失败')
        res.send({
            status:200,
            msg:'新增文章成功'
        })
    })
}
//删除文章
exports.deleteArticle=(req,res)=>{
    const sql='update ev_article set is_delete=1 where id=?'
    db.query(sql,[req.params.id],(err,result)=>{
        if(err) return res.cc(err.message)
        if(result.affectedRows!==1) return res.cc('删除文章失败')
        res.send({
            status:200,
            msg:'删除文章成功'
        })
    })
}
//修改文章
exports.updateArticle=(req,res)=>{
    const sql='update ev_article set title=?,cate_id=?,content=?,state=?,cover_img=? where id=?'
    db.query(sql,[req.body.title,req.body.cate_id,req.body.content,req.body.state,req.body.cover_img,req.params.id],(err,result)=>{
        if(err) return res.cc(err.message)
        if(result.affectedRows!==1) return res.cc('修改文章失败')
        res.send({
            status:200,
            msg:'修改文章成功'
        })
    })
}
//查询文章
exports.getArticle=(req,res)=>{
    const sql='select * from ev_article order by pub_date desc'
    db.query(sql,(err,result)=>{
        if(err) return res.cc(err.message)
        if(result.length==0) return res.cc('查询文章失败')
        res.send({
            status:200,
            msg:'查询文章成功',
            data:result
        })
    })
}

